<?php


namespace app\common\library\storage;

use think\Exception;
use think\facade\Filesystem;
use think\File;

class Storage
{
    private $config;

    /**
     * @var string
     */
    private $disk;

    /**
     * @var Driver
     */
    private $engine;

    /**
     * construct method.
     *
     * @param array $config
     */
    public function __construct(array $config = [])
    {
        $disks = Filesystem::getConfig('disks');
        $this->config = array_merge($disks, $config);
    }

    /**
     * set driver.
     *
     * @param string $driver
     *
     * @return Driver
     */
    public function driver($disk = null)
    {
        if (is_null(Filesystem::getDiskConfig($disk))) {
            //throw new Exception("Driver [$disk]'s Config is not defined.");
            $disk = Filesystem::getDefaultDriver();
        }

        $this->disk = $disk;
        $this->engine = $this->build($disk);

        return $this->engine;
    }

    /**
     * build engine
     *
     * @param string $driver
     *
     * @return Driver
     *
     */
    protected function build($disk)
    {
        $class = '\\app\\common\\library\\storage\\engine\\' . ucfirst($disk);
        return new $class($disk, $this->config[$disk]);
    }
}
